package com.lzx.guanchajava.view.widget

import android.content.BroadcastReceiver
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.view.View
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import androidx.appcompat.widget.AppCompatImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.lzx.guanchajava.R
import com.lzx.guanchajava.pojo.TAG
import com.lzx.guanchajava.util.App
import com.lzx.guanchajava.util.ResourceUtil
import org.jetbrains.anko.defaultSharedPreferences
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method


/**
 * 圆形https://blog.csdn.net/RockyHua/article/details/79416085
 */
const val ACTION_LOAD_IMAGE = "ACTION_LOAD_IMAGE"
public class UrlImageView : AppCompatImageView {

    companion object {
        private val mGlide by lazy { Glide.with(App.getContext()) }
    }



    var showAlways = false  //一直显示.不受无图模式影响
    var url : String? = ""
        set(value) {
            field = value
            loadImage()
        }

    private lateinit var mOnLongClickListener: OnLongClickListener
    private var mShowHolder = false     //是否显示占位图。显示占位图时,点击占位图加载原图

    //画笔
    private var mPaint = Paint()
    //圆形图片的半径
    private var mRadius: Float = 0f
    //图片的宿放比例
    private var mScale: Float = 0f

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.UrlImageView)


        ta?.let {
            val N = it.indexCount
            for (x in 0 .. N) {
                when(val attr = it.getIndex(x)) {
                    R.styleable.UrlImageView_url -> url = it.getString(attr)

                    R.styleable.UrlImageView_ifCircle -> ifCircle = it.getBoolean(attr, false)

                    R.styleable.UrlImageView_onLongClick -> {
                        check(!context.isRestricted) {
                            ("The android:onClick attribute cannot "
                                    + "be used within a restricted context")
                        }

                        val handlerName: String? = ta.getString(attr)
                        handlerName?.let {
                            setOnLongClickListener(DeclaredOnLongClickListener(this, it))
                        }
                    }
                }
            }
            ta.recycle()
        }

    }

    constructor(context: Context) : super(context)

    /*public fun setOnLongClickListener(onLongClickListener: OnLongClickListener) {
        mOnLongClickListener = onLongClickListener
    }*/

    var ifCircle = false

    private fun loadImage() {
        if (!App.getContext().defaultSharedPreferences.getBoolean("pref_no_pic", false) || showAlways) {
            loadFromNet()
            mShowHolder = false
        } else {
            loadFromPalceholder()
            mShowHolder = true
        }
    }

    private fun loadFromNet() {
        mGlide.load(url)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(this)
    }
    private fun loadFromPalceholder() {
        setImageDrawable(context.getDrawable(R.drawable.img_placeholder))
    }

    override fun setOnClickListener(l: OnClickListener?) {
        if (mShowHolder) {
            loadFromNet()
        }
        super.setOnClickListener(l)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (ifCircle) {
            //由于是圆形，宽高应保持一致
            val size = Math.min(measuredWidth, measuredHeight)
            mRadius = (size / 2).toFloat()
            setMeasuredDimension(size, size)
        }
    }

    override fun onDraw(canvas: Canvas) {
        if (null != drawable && ifCircle) {
            mPaint = Paint()

            val drawable = drawable
            if (drawable is BitmapDrawable) {
                val bitmap = drawable.bitmap
                //初始化BitmapShader，传入bitmap对象
                val bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
                //计算缩放比例
                mScale = if (bitmap != null) mRadius * 2.0f / Math.min(bitmap.height, bitmap.width) else 1f

                val matrix = Matrix()
                matrix.setScale(mScale, mScale)
                bitmapShader.setLocalMatrix(matrix)
                mPaint.shader = bitmapShader
                //画圆形，指定好坐标，半径，画笔
                canvas.drawCircle(mRadius, mRadius, mRadius, mPaint)
            }
        } else {
            super.onDraw(canvas)
        }

        if (App.getContext().defaultSharedPreferences.getBoolean(TAG.PREF_NIGHT_MODE, false))
            canvas.drawColor(ResourceUtil.getColor(R.color.imageForeground))
    }


    inner class ImageBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            loadImage()
        }
    }

    inner class ImageReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent!!.action == ACTION_LOAD_IMAGE) loadImage()
        }

    }


    /**
     * An implementation of OnLongClickListener that attempts to lazily load a
     * named click handling method from a parent or ancestor context.
     */
    private class DeclaredOnLongClickListener(@NonNull hostView: View, @NonNull methodName: String) : OnLongClickListener {
        private val mHostView: View
        private val mMethodName: String
        private var mResolvedMethod: Method? = null
        private var mResolvedContext: Context? = null

        override fun onLongClick(@NonNull v: View): Boolean {
            if (mResolvedMethod == null) {
                resolveMethod(mHostView.context, mMethodName)
                return true
            }
            try {
                mResolvedMethod!!.invoke(mResolvedContext, v)
                return true
            } catch (e: IllegalAccessException) {
                throw IllegalStateException(
                        "Could not execute non-public method for android:onClick", e)
            } catch (e: InvocationTargetException) {
                throw IllegalStateException(
                        "Could not execute method for android:onClick", e)
            }
        }

        @NonNull
        private fun resolveMethod(@Nullable context: Context, @NonNull name: String) {
            var context: Context? = context
            while (context != null) {
                try {
                    if (!context.isRestricted) {
                        val method: Method? = context.javaClass.getMethod(mMethodName, View::class.java)
                        if (method != null) {
                            mResolvedMethod = method
                            mResolvedContext = context
                            return
                        }
                    }
                } catch (e: NoSuchMethodException) {
                    // Failed to find method, keep searching up the hierarchy.
                }
                context = if (context is ContextWrapper) {
                    context.baseContext
                } else {
                    // Can't search up the hierarchy, null out and fail.
                    null
                }
            }
            val id = mHostView.id
            val idText = if (id == NO_ID) "" else " with id '"+ mHostView.context.resources.getResourceEntryName(id) + "'"
            throw IllegalStateException("Could not find method " + mMethodName
                    + "(View) in a parent or ancestor Context for android:onClick "
                    + "attribute defined on view " + mHostView.javaClass + idText)
        }

        init {
            mHostView = hostView
            mMethodName = methodName
        }
    }
}